<template>
  <div class="my-scores-page">
    <!-- 页面头部 -->
    <el-card class="header-card" shadow="never">
      <div class="header-content">
        <div class="title-section">
          <h2>我的成绩</h2>
          <p class="subtitle">查看课程成绩和学分情况</p>
        </div>
        <div class="stats-section">
          <div class="stat-item">
            <div class="stat-value">{{ totalCourses }}</div>
            <div class="stat-label">已修课程</div>
          </div>
          <div class="stat-divider"></div>
          <div class="stat-item">
            <div class="stat-value">{{ totalCredits.toFixed(1) }}</div>
            <div class="stat-label">总学分</div>
          </div>
          <div class="stat-divider"></div>
          <div class="stat-item">
            <div class="stat-value">{{ averageScore.toFixed(1) }}</div>
            <div class="stat-label">平均分</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="学期">
          <el-input 
            v-model="filterForm.semester" 
            placeholder="如：2024-2025-1" 
            clearable
            style="width: 200px"
            @change="loadScores"
          />
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input 
            v-model="filterForm.courseName" 
            placeholder="请输入课程名称" 
            clearable
            style="width: 200px"
            @change="loadScores"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadScores" :icon="Search">
            查询
          </el-button>
          <el-button @click="resetFilter" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成绩列表 -->
    <el-card class="scores-card">
      <template #header>
        <div class="card-header">
          <span>成绩列表</span>
          <div>
            <el-button type="success" size="small" @click="exportScores">
              <el-icon><Download /></el-icon> 导出成绩单
            </el-button>
            <el-button type="primary" size="small" @click="loadScores">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="scoreList" 
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="semester" label="学期" width="150" />
        <el-table-column prop="courseName" label="课程名称" min-width="200" />
        <el-table-column prop="score" label="成绩" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getScoreType(row.score)" size="large">
              {{ row.score }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="100" align="center">
          <template #default="{ row }">
            <span class="credit-text">{{ row.credit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="等级" width="100" align="center">
          <template #default="{ row }">
            <span :class="getScoreClass(row.score)">
              {{ getScoreGrade(row.score) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="录入时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="loadScores"
        @size-change="loadScores"
        class="pagination"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { getMyScores } from '@/api/score'

// 筛选表单
const filterForm = reactive({
  semester: '',
  courseName: ''
})

// 成绩列表
const loading = ref(false)
const scoreList = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 统计数据
const totalCourses = computed(() => scoreList.value.length)
const totalCredits = computed(() => {
  return scoreList.value.reduce((sum, item) => {
    return sum + (Number(item.credit) || 0)
  }, 0)
})
const averageScore = computed(() => {
  if (scoreList.value.length === 0) return 0
  const sum = scoreList.value.reduce((sum, item) => {
    return sum + (Number(item.score) || 0)
  }, 0)
  return sum / scoreList.value.length
})

/**
 * 加载成绩列表
 */
const loadScores = async () => {
  loading.value = true
  try {
    const data = await getMyScores({
      current: currentPage.value,
      size: pageSize.value,
      semester: filterForm.semester || undefined,
      courseName: filterForm.courseName || undefined
    }) as any
    
    if (data) {
      scoreList.value = data.records || []
      total.value = data.total || 0
    }
  } catch (error: any) {
    console.error('加载成绩失败', error)
    ElMessage.error(error?.message || '加载失败')
  } finally {
    loading.value = false
  }
}

/**
 * 重置筛选条件
 */
const resetFilter = () => {
  filterForm.semester = ''
  filterForm.courseName = ''
  currentPage.value = 1
  loadScores()
}

/**
 * 获取成绩标签类型
 */
const getScoreType = (score: number) => {
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 70) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

/**
 * 获取成绩样式类
 */
const getScoreClass = (score: number) => {
  if (score >= 90) return 'grade-excellent'
  if (score >= 80) return 'grade-good'
  if (score >= 70) return 'grade-medium'
  if (score >= 60) return 'grade-pass'
  return 'grade-fail'
}

/**
 * 获取成绩等级
 */
const getScoreGrade = (score: number) => {
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 70) return '中等'
  if (score >= 60) return '及格'
  return '不及格'
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return dateTime.replace('T', ' ').substring(0, 19)
}

/**
 * 导出成绩单
 */
const exportScores = () => {
  const token = localStorage.getItem('token')
  window.open(`/api/score/export-my-scores?satoken=${token}`, '_blank')
  ElMessage.success('正在导出成绩单...')
}

onMounted(() => {
  loadScores()
})
</script>

<style scoped lang="scss">
.my-scores-page {
  padding: 20px;
  background-color: #f5f7fa;

  .header-card {
    margin-bottom: 20px;
    border-radius: 12px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;

    :deep(.el-card__body) {
      padding: 24px;
    }

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 20px;

      .title-section {
        h2 {
          margin: 0 0 8px 0;
          font-size: 28px;
          font-weight: 600;
          color: white;
        }

        .subtitle {
          margin: 0;
          color: rgba(255, 255, 255, 0.9);
          font-size: 14px;
        }
      }

      .stats-section {
        display: flex;
        align-items: center;
        gap: 24px;
        flex-wrap: wrap;

        .stat-item {
          text-align: center;
          padding: 0 12px;

          .stat-value {
            font-size: 32px;
            font-weight: bold;
            color: white;
            line-height: 1;
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 13px;
            color: rgba(255, 255, 255, 0.85);
            white-space: nowrap;
          }
        }

        .stat-divider {
          width: 1px;
          height: 40px;
          background-color: rgba(255, 255, 255, 0.3);
        }
      }
    }
  }

  .filter-card {
    margin-bottom: 20px;
    border-radius: 12px;

    .filter-form {
      margin-bottom: 0;

      :deep(.el-form-item) {
        margin-bottom: 0;
      }
    }
  }

  .scores-card {
    border-radius: 12px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }

    .credit-text {
      font-weight: 600;
      color: #409eff;
      font-size: 16px;
    }

    .grade-excellent {
      color: #67c23a;
      font-weight: bold;
      font-size: 14px;
    }

    .grade-good {
      color: #409eff;
      font-weight: bold;
      font-size: 14px;
    }

    .grade-medium {
      color: #e6a23c;
      font-weight: bold;
      font-size: 14px;
    }

    .grade-pass {
      color: #909399;
      font-weight: bold;
      font-size: 14px;
    }

    .grade-fail {
      color: #f56c6c;
      font-weight: bold;
      font-size: 14px;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  // 响应式
  @media (max-width: 768px) {
    padding: 12px;

    .header-card .header-content {
      flex-direction: column;
      align-items: flex-start;

      .stats-section {
        width: 100%;
        justify-content: space-around;

        .stat-divider {
          display: none;
        }
      }
    }
  }
}
</style>

